<?php
/**
 */
class Yz_Action_SelectListByKey
    extends Yz_Action_SelectList
{

    /** SQL rows limit
     *  @var null
     */
    protected $keyName;

    /** SQL rows offset, default null (unused)
     *  @var null
     */
    protected $keys;


    /************************************
     *          Public methods          *
     ************************************/


    /**
     *  @param int $limit >= 0
     *  @return this
     */
    public function setKey( $keyName, $keys )
    {
        debug();
        $this->keyName = Yz_String::testNotEmpty($keyName);
        if (! $keys)
            throw Yz_Action_Exception::_new('Keys must be non-empty');
        if (is_array($keys))
            if (1 == count($keys))
                $keys = current($keys);
        $this->keys = $keys;
        return $this;
    }



    /************************************
     *        Protected methods         *
     ************************************/

    /** Verify any arguments before building query
     *      verify the keys
     *  @return this
     */
    protected function verifyArguments()
    {
        debug();
        parent::verifyArguments();
        if (! $this->keyName)
            throw Yz_Action_Exception::_new();
        return $this;
    }


    /**
     *  Apply the arguments to the SQL statement
     *      Setup limit to avoid occasional selection of all rows
     *  @param Yz_SQL_Statement $sql
     *  @return this
     */
    protected function applyArguments(Yz_SQL_Statement $sql)
    {
        debug();
        parent::applyArguments($sql);
        $key = $this->keyName;
        if (is_array($this->keys))
            $sql->where("{$key} IN (" . join(',', $this->keys) . ')');
        else
            $sql->where("{$key}=:_{$key}")
                ->bind("_{$key}", $this->keys)
            ;
        return $this;
    }


}
